#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import, division, print_function
import json
from qcloudsms_py import util
from qcloudsms_py.httpclient import HTTPRequest
from qcloudsms_py.httpclient import HTTPError
from utils.logger import Md_Debug
# from utils.tel_num import TEL_NUM

class SmsSingleSender(object):

    def __init__(self, appid, appkey):
        self._appid = appid
        self._appkey = appkey
        self._url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms";

    def send(self, sms_type, nation_code, phone_number, msg,
             extend="", ext=""):
        """Send single SMS message.（发送SMS消息单）

        :param msg_type: SMS message type, Enum{0: normal SMS, 1: marketing SMS}
        :param nation_code: nation dialing code, e.g. China is 86, USA is 1
        :param phone_number: phone number
        :param msg: SMS message content
        :param extend: extend field, default is empty string
        :param ext: ext field, content will be returned by server as it is
        """
        rand = util.get_random()
        now = util.get_current_time()
        url = "{}?sdkappid={}&random={}".format(
            self._url, self._appid, rand)
        req = HTTPRequest(
            url=url,
            method="POST",
            headers={"Content-Type": "application/json"},
            body={
                "tel": {
                    "nationcode": str(nation_code),
                    "mobile": str(phone_number)
                },
                "type": int(sms_type),
                "msg": str(msg),
                "sig": util.calculate_signature(
                    self._appkey, rand, now, [phone_number]),
                "time": now,
                "extend": str(extend),
                "ext": str(ext)
            },
            connect_timeout=60,
            request_timeout=60
        )
        return util.api_request(req)

    def send_with_param(self, nation_code, phone_number, template_id,
                        params, sign="", extend="", ext=""):
        """Send single SMS message with template paramters.（发送带有模板参数的单个SMS消息）

        :param nation_code: nation dialing code, e.g. China is 86, USA is 1
        （国家代码：国家拨号代码，例如中国86，美国是1）
        :param phone_number: phone number
        :param template_id: template id（模板编号）
        :param params: template parameters（模板参数）
        :param sign: Sms user sign（短信用户签署）
        :param extend: extend field, default is empty string（扩展场，默认为空字符串）
        :param ext: ext field, content will be returned by server as it is（下一个字段，内容将由服务器返回）
        """
        try:
            rand = util.get_random()
            now = util.get_current_time()
            url = "{}?sdkappid={}&random={}".format(
                self._url, self._appid, rand)
            req = HTTPRequest(
                url=url,
                method="POST",
                headers={"Content-Type": "application/json"},
                body={
                    "tel": {
                        "nationcode": str(nation_code),
                        "mobile": str(phone_number)
                    },
                    "sign": str(sign),
                    "tpl_id": int(template_id),
                    "params": params,
                    "sig": util.calculate_signature(
                        self._appkey, rand, now, [phone_number]),
                    "time": now,
                    "extend": str(extend),
                    "ext": str(ext)
                },
                connect_timeout=60,
                request_timeout=60
            )
        except Exception as e:
            print(e)
            Md_Debug.info(util.api_request(req))
        return util.api_request(req)



class SmsMultiSender(object):

    def __init__(self, appid, appkey):
        self._appid = appid
        self._appkey = appkey
        self._url = "https://yun.tim.qq.com/v5/tlssmssvr/sendmultisms2"

    def send(self, sms_type, nation_code, phone_numbers, msg,
             extend="", ext=""):

        """Send a SMS messages to multiple phones at once.(立即向多个电话发送SMS消息)

        :param number: SMS message type, Enum{0: normal SMS, 1: marketing SMS}
        :param nation_code: nation dialing code, e.g. China is 86, USA is 1
        :param phone_numbers: phone number array
        :param msg: SMS message content
        :param extend: extend field, default is empty string
        :param ext: ext field, content will be returned by server as it is
        """
        rand = util.get_random()
        now = util.get_current_time()
        url = "{}?sdkappid={}&random={}".format(
            self._url, self._appid, rand)
        req = HTTPRequest(
            url=url,
            method="POST",
            headers={"Content-Type": "application/json"},
            body={
                "tel": [{"nationcode": nation_code, "mobile": pn}
                        for pn in phone_numbers],
                "type": int(sms_type),
                "msg": str(msg),
                "sig": util.calculate_signature(
                    self._appkey, rand, now, phone_numbers),
                "time": now,
                "extend": str(extend),
                "ext": str(ext)
            },
            connect_timeout=60,
            request_timeout=60
        )
        return util.api_request(req)

    def send_with_param(self, nation_code, phone_numbers, template_id,
                        params, sign="", extend="", ext=""):
        """
        Send a SMS messages with template parameters to multiple
        phones at once.（发送带有模板参数的SMS消息到多个）

        :param nation_code: nation dialing code, e.g. China is 86, USA is 1
        :param phone_numbers: multiple phone numbers
        :param template_id: template id
        :param params: template parameters
        :param sign: Sms user sign
        :param extend: extend field, default is empty string
        :param ext: ext field, content will be returned by server as it is
        """
        rand = util.get_random()
        now = util.get_current_time()
        url = "{}?sdkappid={}&random={}".format(
            self._url, self._appid, rand)
        req = HTTPRequest(
            url=url,
            method="POST",
            headers={"Content-Type": "application/json"},
            body={
                "tel": [{"nationcode": nation_code, "mobile": pn}
                        for pn in phone_numbers],
                "sign": sign,
                "tpl_id": int(template_id),
                "params": params,
                "sig": util.calculate_signature(
                    self._appkey, rand, now, phone_numbers),
                "time": now,
                "extend": str(extend),
                "ext": str(ext)
            },
            connect_timeout=60,
            request_timeout=60
        )
        return util.api_request(req)


class SmsStatusPuller(object):

    def __init__(self, appid, appkey):
        self._appid = appid
        self._appkey = appkey
        self._url = "https://yun.tim.qq.com/v5/tlssmssvr/pullstatus"

    def _pull(self, sms_type, max_num):
        """Pull SMS message status.（短信状态。）

        :param msg_type: SMS message type, Enum{0: normal SMS, 1: marketing SMS}
        :param max_num: maximum number of message status
        """
        rand = util.get_random()
        now = util.get_current_time()
        url = "{}?sdkappid={}&random={}".format(
            self._url, self._appid, rand)
        req = HTTPRequest(
            url=url,
            method="POST",
            headers={"Content-Type": "application/json"},
            body={
                "sig": util.calculate_signature(
                    self._appkey, rand, now),
                "time": now,
                "type": sms_type,
                "max": max_num
            },
            connect_timeout=60,
            request_timeout=60
        )
        return util.api_request(req)

    def pull_callback(self, max_num):
        """Pull callback SMS messages status.（获取回调SMS消息状态）

        :param max_num: maximum number of message status
        """
        return self._pull(0, max_num)

    def pull_reply(self, max_num):
        """Pull reply SMS messages status.

        :param max_num: maximum number of message status
        """
        return self._pull(1, max_num)


class SmsMobileStatusPuller(object):

    def __init__(self, appid, appkey):
        self._appid = appid;
        self._appkey = appkey;
        self._url = "https://yun.tim.qq.com/v5/tlssmssvr/pullstatus4mobile"

    def _pull(self, msg_type, nation_code, mobile, begin_time, end_time, max_num):
        """Pull SMS messages status for single mobile.

        :param msg_type: SMS message type, Enum{0: normal SMS, 1: marketing SMS}
        :param nation_code: nation dialing code, e.g. China is 86, USA is 1
        :param mobile: mobile number
        :param begin_time: begin time, unix timestamp
        :param end_time: end time, unix timestamp
        :param max_num: maximum number of message status
        """
        rand = util.get_random()
        now = util.get_current_time()
        url = "{}?sdkappid={}&random={}".format(
            self._url, self._appid, rand)
        req = HTTPRequest(
            url=url,
            method="POST",
            headers={"Content-Type": "application/json"},
            body={
                "sig": util.calculate_signature(
                    self._appkey, rand, now),
                "type": msg_type,
                "time": now,
                "max": max_num,
                "begin_time": begin_time,
                "end_time": end_time,
                "nationcode": str(nation_code),
                "mobile": str(mobile)
            },
            connect_timeout=60,
            request_timeout=60
        )
        return util.api_request(req)

    def pull_callback(self, nation_code, mobile, begin_time,
                      end_time, max_num):
        """Pull callback SMS message status for single mobile.

        :param nation_code: nation dialing code, e.g. China is 86, USA is 1
        :param mobile: mobile number
        :param begin_time: begin time, unix timestamp
        :param end_time: end time, unix timestamp
        :param max_num: maximum number of message status
        """
        return self._pull(0, nation_code, mobile,
                          begin_time, end_time, max_num)

    def pull_reply(self, nation_code, mobile, begin_time,
                   end_time, max_num):
        """Pull reply SMS message status for single mobile.

        :param nation_code: nation dialing code, e.g. China is 86, USA is 1
        :param mobile: mobile number
        :param begin_time: begin time, unix timestamp
        :param end_time: end time, unix timestamp
        :param max_num: maximum number of message status
        """
        return self._pull(1, nation_code, mobile,
                          begin_time,end_time, max_num)


def sms_public(sign, content_param_w):
    """
    短信调用接口(测试模板id：54271)
    短信发送公共接口(0:租金提醒——网咖用户；1:欠费告警——网咖用户；2：欠费告警——渠道商用户；
                3: 开机率告警——网咖用户；4：开机率告警——渠道商用户；
                5: 解锁超时告警——网咖用户；6：解锁超时告警——渠道商用户；
                7: 主机故障告警——网咖用户；8：主机故障告警——渠道商用户；
                9: 资料初审未通过——渠道商用户；10：资料复审未通过——渠道商用户；
                11: 设备定位异常——网咖用户； 12：设备定位异常——渠道商用户；
                13：设备定位异常——运营人员； 14 设备定位异常——租赁公司；
                15: 用户创建账号——所有用户；   16: 发送短信验证码——所有用户；
                17:设备自检异常——网咖用户； 18：设备自检异常——渠道商用户；
                19：设备自检异常——运营人员； 20：设备自检异常——租赁公司
                21：用户创建账号——所有用户；
                22：复审通过后通知网咖用户、渠道签订线下合同——网咖用户；
                23：复审通过后给网咖用户发送用户信息——网咖用户；
                24：复审通过后通知网咖用户、渠道签订线下合同——渠道商用户；
                25：云平台验收——网咖用户；
                26: 主机异常——网咖用户；  27：主机异常——渠道商用户；
                28: 主机异常——运营人员；  29：主机异常——租赁公司用户；)
    :return:
    """
    appid = 1400144263
    appkey = "9bb28934f0de8a4df3c6321db098f8a4"
    ssender = SmsSingleSender(appid, appkey)
    result = {}
    if sign == 0:
        template_id = 129229
        params = [content_param_w['w_real_name'], str(content_param_w['plan_date']),
                  str(round(float(content_param_w['pay_amount']), 2)), TEL_NUM]
        try:
            result = ssender.send_with_param(86, content_param_w['w_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e.message)
        except Exception as e:
            print(e.message)
        return result
    if sign == 1:
        template_id = 129232
        params = [content_param_w['w_real_name'], str(content_param_w['plan_date']),
                  str(round(float(content_param_w['sum_free']), 2)), TEL_NUM]
        try:
            result = ssender.send_with_param(86, content_param_w['w_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 2:
        template_id = 129234
        params = [content_param_w['q_real_name'], str(content_param_w['plan_date']), content_param_w['netbar_name'],
                  str(round(float(content_param_w['sum_free']), 2)), TEL_NUM]
        try:
            result = ssender.send_with_param(86, content_param_w['q_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 3:
        template_id = 129237
        params = [content_param_w['w_real_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['w_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 4:
        template_id = 129238
        params = [content_param_w['q_real_name'], content_param_w['netbar_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['q_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 5:
        template_id = 129239
        params = [content_param_w['w_real_name'], content_param_w['device_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['w_mobile'],
                                             template_id, params)
            print(result)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        print(result)
        return result
    if sign == 6:
        template_id = 129242
        params = [content_param_w['q_real_name'], content_param_w['netbar_name'], content_param_w['device_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['q_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 7:
        template_id = 129244
        params = [content_param_w['w_real_name'], content_param_w['device_name'], content_param_w['breakdown_reason']]
        try:
            result = ssender.send_with_param(86, content_param_w['w_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 8:
        template_id = 129245
        params = [content_param_w['q_real_name'], content_param_w['netbar_name'], content_param_w['device_name'],
                  content_param_w['breakdown_reason']]
        try:
            result = ssender.send_with_param(86, content_param_w['q_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 9:
        template_id = 129216
        params = [content_param_w['channel_name'], content_param_w['netbar_name'], content_param_w['result'],
                  TEL_NUM]
        try:
            result = ssender.send_with_param(86, content_param_w['q_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 10:
        template_id = 129219
        params = [content_param_w['channel_name'], content_param_w['netbar_name'], content_param_w['result'],
                  TEL_NUM]
        try:
            result = ssender.send_with_param(86, content_param_w['q_moblie'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 11:
        template_id = 133126
        params = [content_param_w['w_real_name'], content_param_w['device_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['w_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 12:
        template_id = 133127
        params = [content_param_w['q_real_name'], content_param_w['netbar_name'],content_param_w['device_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['q_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 13:
        template_id = 133129
        params = [content_param_w['y_real_name'], content_param_w['netbar_name'],content_param_w['device_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['y_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 14:
        template_id = 133131
        params = [content_param_w['z_real_name'], content_param_w['netbar_name'],content_param_w['device_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['z_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 15:
        template_id = 133138
        params = [content_param_w['username']]
        try:
            result = ssender.send_with_param(86, content_param_w['mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 16:
        template_id = 129243
        params = [content_param_w['mobile_code'], 2]
        try:
            result = ssender.send_with_param(86, content_param_w['mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 17:
        template_id = 133132
        params = [content_param_w['w_real_name'], content_param_w['device_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['w_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 18:
        template_id = 133134
        params = [content_param_w['q_real_name'], content_param_w['netbar_name'], content_param_w['device_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['q_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 19:
        template_id = 133135
        params = [content_param_w['y_real_name'], content_param_w['netbar_name'], content_param_w['device_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['y_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 20:
        template_id = 133136
        params = [content_param_w['z_real_name'], content_param_w['netbar_name'],content_param_w['device_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['z_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 21:
        template_id = 139075
        params = [content_param_w['user_name'], content_param_w['password']]
        try:
            result = ssender.send_with_param(86, content_param_w['mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 22:
        template_id = 129223
        params = [content_param_w['netbar_user_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['n_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 23:
        template_id = 129220
        params = [content_param_w['netbar_user_name'], content_param_w['n_mobile'], content_param_w['password']]
        try:
            result = ssender.send_with_param(86, content_param_w['n_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 24:
        template_id = 129226
        params = [content_param_w['channel_name'], content_param_w['netbar_name']]
        try:
            result = ssender.send_with_param(86, content_param_w['q_moblie'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 25:
        template_id = 170709
        params = [content_param_w['netbar_name'], content_param_w['begin_date']]
        try:
            result = ssender.send_with_param(86, content_param_w['n_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result
    if sign == 26:
        template_id = 170709
        params = [content_param_w['w_real_name'], content_param_w['device_name'], content_param_w['device_resion']]
        try:
            result = ssender.send_with_param(86, content_param_w['w_mobile'],
                                             template_id, params)
        except HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        return result

if __name__ == "__main__":
    # sms_public("18391352252", 54271, ["测试"])
    content_param_w = {"netbar_name": "123456",
                       "begin_date": "123",
                       "n_mobile": "18391352252"}
    ret = sms_public(25, content_param_w)
    print (ret)
    # appid = 1400048767
    # appkey = "1f25cee678baf79aa77bcc8f362b4d8a"
    # phone_numbers = ["18391352252"]
    # template_id = 54271
    #
    # ssender = SmsSingleSender(appid, appkey)
    # params = ["789456"]
    # print(phone_numbers[0])
    # print(template_id)
    # print(params)
    # try:
    #     result = ssender.send_with_param(86, phone_numbers[0],
    #                                      template_id, params)
    # except HTTPError as e:
    #     print(e)
    # except Exception as e:
    #     print(e)
    # print(result)